﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using thinger.CommunicationLib;
using thinger.ConfigLib;
using thinger.DataConvertLib;
using thinger.ToolsLib;
using xiaoxiong.KYJDAL.Models;

namespace xiaoxiong.ScadaProModbusRtu.Common
{
    public class CommonMethods
    {
        //全局登录对象
        public static SysAdmin CommonAdmin = null;
        //全局设备对象
        public static ModbusRTUDevice plcDevice;
        //通信对象
        public static ModbusRTU plc = new ModbusRTU();
        //全局设置对象
        public static SysConfig sysConfig = new SysConfig();

        /// <summary>
        /// 滴答次数
        /// </summary>
        public static int tickCount = 0;
        /// <summary>
        /// 读取配置文件
        /// </summary>
        public static void GetSysConfig()
        {
            try
            {
                sysConfig.AutoStart = Convert.ToBoolean(IniConfigHelper.ReadIniData("配置信息", "开机自动启动", "False"));
                sysConfig.AutoLogin = Convert.ToBoolean(IniConfigHelper.ReadIniData("配置信息", "启用自动登录", "False"));
                sysConfig.AutoLock = Convert.ToBoolean(IniConfigHelper.ReadIniData("配置信息", "无操作自动锁屏", "False"));
                sysConfig.LockPeriod = Convert.ToInt32(IniConfigHelper.ReadIniData("配置信息", "锁屏间隔时间", "False"));
                sysConfig.ShowSeriesCount = Convert.ToInt32(IniConfigHelper.ReadIniData("配置信息", "曲线显示数量", "False"));
            }
            catch(Exception e)
            {
                sysConfig = null;
            }           
        }
        /// <summary>
        /// 保存自动启动
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool SaveAutoStart(bool value)
        {
            return IniConfigHelper.WriteIniData("配置信息", "开机自动启动",value.ToString());
        }
        /// <summary>
        /// 保存自动登录
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool SaveAutoLogin(bool value)
        {
            return IniConfigHelper.WriteIniData("配置信息", "启用自动登录", value.ToString());
        }
        /// <summary>
        /// 无操作自动锁屏
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool SaveAutoLock(bool value)
        {
            return IniConfigHelper.WriteIniData("配置信息", "无操作自动锁屏", value.ToString());
        }

        /// <summary>
        /// 保存无操作自动锁屏
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool SaveLockPeriod(int value)
        {
            return IniConfigHelper.WriteIniData("配置信息", "锁屏间隔时间", value.ToString());
        }
        /// <summary>
        /// 保存曲线显示数量
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool SaveShowSeriesCount(int value)
        {
            return IniConfigHelper.WriteIniData("配置信息", "曲线显示数量", value.ToString());
        }


        //全局当前时间
        public static string CurrentTime
        {
            get { return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); }
        }
        //写入日志
        public static void AddLog(bool isError,string info)
        {
            if(AddLogDelegate != null)
            {
                AddLogDelegate?.Invoke(isError, info);
            }
        }
        //添加操作日志
        public static void AddOpLog(bool isError, string info)
        {
            if (AddOpLogDelegate != null)
            {
                AddOpLogDelegate?.Invoke(isError, info);
            }
        }
        //添加报警日志
        //public static void AddAlarmLog(bool isError, string info)
        //{
        //    if (AddAlarmLogDelegate != null)
        //    {
        //        AddAlarmLogDelegate?.Invoke(isError, info);
        //    }
        //}



        //创建日志委托
        public static Action<bool, string> AddLogDelegate;
        public static Action<bool, string> AddOpLogDelegate;

        public static OperateResult CommonWrite(string varName,string varValue)
        {

            var variable = plcDevice.VarList.Where(c => c.VarName == varName).FirstOrDefault();
            if (variable != null)
            {
                try
                {
                    DataType type = (DataType)Enum.Parse(typeof(DataType), variable.VarType);
                    var result = MigrationLib.SetMigrationValue(varValue, type, variable.Scale.ToString(), variable.Offset.ToString());
                    if (result.IsSuccess)
                    {
                        //写入设备
                        switch (type)
                        {
                            case DataType.Bool:
                                return plc.WriteBool(variable.VarAddress, Convert.ToBoolean(result.Content), variable.VarAddress.Split('.').Length == 3);
                            case DataType.Byte:
                                return plc.WriteByte(variable.VarAddress, Convert.ToByte(result.Content));
                            case DataType.Short:
                                return plc.WriteShort(variable.VarAddress, Convert.ToInt16(result.Content));
                            case DataType.UShort:
                                return plc.WriteUShort(variable.VarAddress, Convert.ToUInt16(result.Content));
                            case DataType.Int:
                                return plc.WriteInt(variable.VarAddress, Convert.ToInt32(result.Content));
                            case DataType.UInt:
                                return plc.WriteUInt(variable.VarAddress, Convert.ToUInt32(result.Content));
                            case DataType.Float:
                                return plc.WriteFloat(variable.VarAddress, Convert.ToSingle(result.Content));
                            case DataType.Double:
                                return plc.WriteDouble(variable.VarAddress, Convert.ToDouble(result.Content));
                            case DataType.Long:
                                return plc.WriteLong(variable.VarAddress, Convert.ToInt64(result.Content));
                            case DataType.ULong:
                                return plc.WriteULong(variable.VarAddress, Convert.ToUInt64(result.Content));
                            case DataType.String:
                                return plc.WriteString(variable.VarAddress, result.Content);
                            case DataType.ByteArray:
                                return plc.WriteByteArray(variable.VarAddress, ByteArrayLib.GetByteArrayFromHexString(result.Content));
                            default:
                                return OperateResult.CreateFailResult("不支持的设备类型");
                        }
                    }
                    else
                    {
                        return OperateResult.CreateFailResult(result.Message);
                    }
                }
                catch (Exception e)
                {
                    return OperateResult.CreateFailResult($"Error: {e.Message}");
                }            
            }else
            {
               return OperateResult.CreateFailResult("变量不存在");
            }
        }

        internal static bool SaveLockPeriod(float currentValue)
        {
            throw new NotImplementedException();
        }
    }
}
